import Vuex from 'vuex'
import Vue from 'vue'
import getters from './getters'
import actions from './actions'
import { TOKEN, OPENID, NOTICEID } from '@/types/storage'
import { mode } from '@/config/index.js'
import { UPDATE_CATEGORY_LIST } from '@/types/globalEventName'
// import order from './modules/order.js'

// import {loginOut} from '@/api/user.js'
// 购物车在tabbar 的下标
const SHOPPING_CART_TAB_INDEX = 3

Vue.use(Vuex)
let tokenInit = ''
let openId = ''
try {
  let token = uni.getStorageSync(TOKEN)
  let id = uni.getStorageSync(OPENID)
  if (token) {
    tokenInit = token
  }
  openId = id ? id : ''
} catch (e) {}
export default new Vuex.Store({
  modules: {},
  state: {
    userInfo: {},
    token: tokenInit,
    cartGoodsNum: 0, // 购物车商品数量
    openId: openId,
    unreadData: [] // 已读公告
  },
  mutations: {
    // 设置用户信息
    SET_USER_INFO(state, data = {}) {
      console.log('---store 更新用户信息')
      state.userInfo = data
    },
    /**
     * 设置token
     * @param {Object} state
     * @param {String} data - 设置的token
     * */
    SET_USER_TOKEN(state, data) {
      state.token = data
      uni.setStorageSync(TOKEN, data)
    },

    LOGIN_OUT(state) {
      state.token = ''
      state.userInfo = {}
      state.cartGoodsNum = 0
      uni.removeTabBarBadge({
        index: SHOPPING_CART_TAB_INDEX
      })
      uni.removeStorageSync(TOKEN)
    },
    // 设置购物车商品数量
    SET_CART_NUM(state, data = 0) {
      state.cartGoodsNum = data
      if (data > 0) {
        console.log('---更新购物车商品数量---', data > 99 ? '99+' : data + '')
        uni.setTabBarBadge({
          index: SHOPPING_CART_TAB_INDEX,
          text: data > 99 ? '99+' : data + ''
        })
      } else {
        uni.removeTabBarBadge({
          index: SHOPPING_CART_TAB_INDEX
        })
      }
    },
    //
    SET_OPEN_ID(state, id) {
      state.openId = id
      uni.setStorageSync(OPENID, id)
    },
    // 设置已读公告
    GET_NOTICE_DATA(state, data = {}) {
      let arr = uni.getStorageSync(NOTICEID) || state.unreadData
      console.log(data, '----全部公告')
      console.log(arr, '----已读公告')
      let array = []
      let num = 0
      data.map((item) => {
        if (arr.indexOf(item) != -1) {
          // 已读里面存在的
          array.push(item)
        } else {
          // 已读里面不存在的
          num++
        }
      })
      if (num > 0) {
        uni.showTabBarRedDot({
          index: 2
        })
      } else {
        uni.hideTabBarRedDot({
          index: 2
        })
      }
      console.log(array, num, '---store 更新已读公告')
    },
    SET_NOTICE_DATA(state, data) {
      let arr = uni.getStorageSync(NOTICEID) || state.unreadData
      arr.push(data)
      uni.setStorageSync(NOTICEID, Array.from(new Set(arr)))
    }
  },
  getters: getters,
  actions: actions,
  strict: mode !== 'prod'
})
